package com.example.book.viewmodel

import androidx.core.text.isDigitsOnly
import androidx.lifecycle.*
import com.example.book.model.Book
import com.example.book.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class BookViewModel @Inject constructor(private val repository: BookRepository) : ViewModel() {

    lateinit var book : LiveData<Book>

    lateinit var books: LiveData<List<Book>>

    lateinit var totalPrice: LiveData<Int>

    lateinit var totalSize: LiveData<Int>

    init {
        viewModelScope.launch {
            books  = repository.getAll().asLiveData()
            book = Transformations.map(books){ it -> it.lastOrNull()}
            totalPrice = Transformations.switchMap(books) { it -> BookViewModel.totalPrice(it) }
            totalSize = Transformations.switchMap(books){ it -> MutableLiveData<Int> (it.size)}
        }
    }

    companion object {
        fun totalPrice(books: List<Book>): LiveData<Int> {
            var sum = 0
            books.forEach {
                if (it.price.isDigitsOnly()) {
                    sum += it.price.toInt()
                }
            }
            return MutableLiveData<Int> (sum)
        }
    }

    //Launching a new coroutine to insert the data in a non-blocking way
    fun add(book: Book) =  viewModelScope.launch{
        repository.insert(*arrayOf(book))
    }

    fun remove(isbn: String) =  viewModelScope.launch{
        repository.delete(isbn)
    }

    fun updatePrice(isbn:String, price:String) =  viewModelScope.launch{
        repository.update(isbn,price)
    }

    class Factory(private val repository: BookRepository) : ViewModelProvider.Factory{

        override fun <T : ViewModel?> create(modelClass: Class<T>): T {

            if(modelClass.isAssignableFrom(BookViewModel::class.java)){
                @Suppress("UNCHECKED_CAST")
                return BookViewModel(repository) as T
            }

            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
}